import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Button, 
  Input, 
  Card, 
  message, 
  Typography, 
  Space, 
  Divider, 
  Tag,
  Popconfirm,
  Tabs,
  Tooltip,
  Modal,
  Form,
  Select,
  Alert,
  Row,
  Col
} from 'antd';
import { 
  DeleteOutlined, 
  PlusOutlined, 
  SearchOutlined, 
  StopOutlined, 
  PhoneOutlined,
  TagOutlined,
  ExclamationCircleOutlined,
  ClockCircleOutlined,
  CommentOutlined,
  UserOutlined
} from '@ant-design/icons';
import api from '../../../services/api';

const { Title, Text } = Typography;
const { Option } = Select;

const BlacklistSettings = () => {
  const [activeTab, setActiveTab] = useState('1');
  const [phoneBlacklist, setPhoneBlacklist] = useState([]);
  const [contentBlacklist, setContentBlacklist] = useState([]);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [modalVisible, setModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [formType, setFormType] = useState('phone'); // 'phone' or 'content'

  // 在组件加载时获取黑名单数据
  useEffect(() => {
    fetchBlacklistData();
  }, []);

  // 获取黑名单数据
  const fetchBlacklistData = async () => {
    setLoading(true);
    try {
      // 从后端获取黑名单数据
      const response = await api.get('/admin/settings/blacklist');
      setPhoneBlacklist(response.data.phones || []);
      setContentBlacklist(response.data.contents || []);
      setLoading(false);
    } catch (error) {
      console.error('获取黑名单数据失败:', error);
      message.error('获取黑名单数据失败，请稍后再试');
      setPhoneBlacklist([]);
      setContentBlacklist([]);
      setLoading(false);
    }
  };

  // 删除电话号码黑名单项
  const deletePhoneBlacklist = async (id) => {
    try {
      // 调用API删除黑名单项
      await api.delete(`/admin/settings/blacklist/phone/${id}`);
      
      // 更新状态
      setPhoneBlacklist(phoneBlacklist.filter(item => item.id !== id));
      message.success('黑名单项已删除');
    } catch (error) {
      console.error('删除黑名单项失败:', error);
      message.error('删除黑名单项失败，请稍后再试');
    }
  };

  // 删除内容黑名单项
  const deleteContentBlacklist = async (id) => {
    try {
      // 调用API删除黑名单项
      await api.delete(`/admin/settings/blacklist/content/${id}`);
      
      // 更新状态
      setContentBlacklist(contentBlacklist.filter(item => item.id !== id));
      message.success('黑名单项已删除');
    } catch (error) {
      console.error('删除黑名单项失败:', error);
      message.error('删除黑名单项失败，请稍后再试');
    }
  };

  // 打开添加黑名单项模态框
  const showAddModal = (type) => {
    setFormType(type);
    form.resetFields();
    setModalVisible(true);
  };

  // 关闭模态框
  const handleCancel = () => {
    setModalVisible(false);
  };

  // 添加黑名单项
  const handleAdd = async (values) => {
    try {
      // 调用API添加黑名单项
      const response = await api.post('/admin/settings/blacklist', values);
      
      // 更新状态
      if (formType === 'phone') {
        setPhoneBlacklist([...phoneBlacklist, response.data]);
      } else {
        setContentBlacklist([...contentBlacklist, response.data]);
      }
      
      setModalVisible(false);
      message.success('黑名单项已添加');
    } catch (error) {
      console.error('添加黑名单项失败:', error);
      message.error('添加黑名单项失败，请稍后再试');
    }
  };

  // 电话号码黑名单表格列定义
  const phoneColumns = [
    {
      title: '电话号码',
      dataIndex: 'phoneNumber',
      key: 'phoneNumber',
      render: (text) => <Space><PhoneOutlined />{text}</Space>,
    },
    {
      title: '原因',
      dataIndex: 'reason',
      key: 'reason',
    },
    {
      title: '添加时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (text) => <Space><ClockCircleOutlined />{text}</Space>,
    },
    {
      title: '添加人',
      dataIndex: 'createdBy',
      key: 'createdBy',
      render: (text) => <Space><UserOutlined />{text}</Space>,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        status === 'active' ? 
          <Tag color="red">已拦截</Tag> : 
          <Tag color="default">已停用</Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Popconfirm
            title="确认删除此黑名单项吗？"
            onConfirm={() => deletePhoneBlacklist(record.id)}
            okText="确认"
            cancelText="取消"
          >
            <Button 
              type="text" 
              danger 
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 内容黑名单表格列定义
  const contentColumns = [
    {
      title: '内容',
      dataIndex: 'content',
      key: 'content',
      render: (text, record) => (
        <Space>
          <CommentOutlined />
          <Tooltip title={record.type === 'regex' ? '正则表达式' : '关键词'}>
            <Text code={record.type === 'regex'}>{text}</Text>
          </Tooltip>
        </Space>
      ),
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (text) => (
        text === 'regex' ? 
          <Tag color="blue">正则表达式</Tag> : 
          <Tag color="green">关键词</Tag>
      ),
    },
    {
      title: '动作',
      dataIndex: 'action',
      key: 'action',
      render: (text) => (
        text === 'block' ? 
          <Tag color="red">拦截</Tag> : 
          <Tag color="orange">标记</Tag>
      ),
    },
    {
      title: '原因',
      dataIndex: 'reason',
      key: 'reason',
    },
    {
      title: '添加时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (text) => <Space><ClockCircleOutlined />{text}</Space>,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        status === 'active' ? 
          <Tag color="red">已启用</Tag> : 
          <Tag color="default">已停用</Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Popconfirm
            title="确认删除此黑名单项吗？"
            onConfirm={() => deleteContentBlacklist(record.id)}
            okText="确认"
            cancelText="取消"
          >
            <Button 
              type="text" 
              danger 
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 过滤电话号码黑名单数据
  const filteredPhoneData = phoneBlacklist.filter(
    item => item.phoneNumber.toLowerCase().includes(searchText.toLowerCase()) ||
    item.reason.toLowerCase().includes(searchText.toLowerCase())
  );

  // 过滤内容黑名单数据
  const filteredContentData = contentBlacklist.filter(
    item => item.content.toLowerCase().includes(searchText.toLowerCase()) ||
    item.reason.toLowerCase().includes(searchText.toLowerCase())
  );

  // 定义Tab项目
  const tabItems = [
    {
      key: '1',
      label: (
        <span>
          <PhoneOutlined /> 电话号码黑名单
        </span>
      ),
      children: (
        <Table 
          columns={phoneColumns} 
          dataSource={filteredPhoneData} 
          rowKey="id" 
          loading={loading}
          pagination={{ pageSize: 10 }}
        />
      )
    },
    {
      key: '2',
      label: (
        <span>
          <TagOutlined /> 内容黑名单
        </span>
      ),
      children: (
        <Table 
          columns={contentColumns} 
          dataSource={filteredContentData} 
          rowKey="id" 
          loading={loading}
          pagination={{ pageSize: 10 }}
        />
      )
    }
  ];

  return (
    <div className="blacklist-settings-container">
      <Card 
        title={
          <Space>
            <StopOutlined />
            <span>黑名单管理</span>
          </Space>
        }
        variant="bordered"
      >
        <Alert
          message="黑名单说明"
          description="黑名单用于管理需要拦截的电话号码和内容关键词。被拦截的电话无法通过系统发送消息，被拦截的内容将被系统自动过滤。"
          type="info"
          showIcon
          style={{ marginBottom: 24 }}
        />
        
        <div style={{ marginBottom: 16 }}>
          <Row gutter={16}>
            <Col span={8}>
              <Input
                placeholder="搜索黑名单内容"
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                prefix={<SearchOutlined />}
                allowClear
              />
            </Col>
            <Col span={16} style={{ textAlign: 'right' }}>
              {activeTab === '1' ? (
                <Button 
                  type="primary" 
                  icon={<PlusOutlined />} 
                  onClick={() => showAddModal('phone')}
                >
                  添加电话黑名单
                </Button>
              ) : (
                <Button 
                  type="primary" 
                  icon={<PlusOutlined />} 
                  onClick={() => showAddModal('content')}
                >
                  添加内容黑名单
                </Button>
              )}
            </Col>
          </Row>
        </div>
        
        <Tabs 
          activeKey={activeTab} 
          onChange={setActiveTab}
          type="card"
          items={tabItems}
        />
      </Card>
      
      {/* 添加黑名单项模态框 */}
      <Modal
        title={formType === 'phone' ? '添加电话号码黑名单' : '添加内容黑名单'}
        open={modalVisible}
        onCancel={handleCancel}
        footer={null}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleAdd}
        >
          {formType === 'phone' ? (
            <>
              <Form.Item
                name="phoneNumber"
                label="电话号码"
                rules={[
                  { required: true, message: '请输入电话号码' },
                  { pattern: /^\d+$/, message: '请输入有效的电话号码' }
                ]}
              >
                <Input placeholder="请输入要拦截的电话号码" prefix={<PhoneOutlined />} />
              </Form.Item>
              <Form.Item
                name="reason"
                label="拦截原因"
                rules={[{ required: true, message: '请输入拦截原因' }]}
              >
                <Input placeholder="请说明拦截此号码的原因" />
              </Form.Item>
            </>
          ) : (
            <>
              <Form.Item
                name="content"
                label="黑名单内容"
                rules={[{ required: true, message: '请输入黑名单内容' }]}
              >
                <Input placeholder="请输入要拦截的关键词或正则表达式" />
              </Form.Item>
              <Form.Item
                name="type"
                label="内容类型"
                rules={[{ required: true, message: '请选择内容类型' }]}
                initialValue="keyword"
              >
                <Select>
                  <Option value="keyword">关键词</Option>
                  <Option value="regex">正则表达式</Option>
                </Select>
              </Form.Item>
              <Form.Item
                name="action"
                label="拦截动作"
                rules={[{ required: true, message: '请选择拦截动作' }]}
                initialValue="flag"
              >
                <Select>
                  <Option value="block">完全拦截</Option>
                  <Option value="flag">标记为敏感</Option>
                </Select>
              </Form.Item>
              <Form.Item
                name="reason"
                label="拦截原因"
                rules={[{ required: true, message: '请输入拦截原因' }]}
              >
                <Input placeholder="请说明拦截此内容的原因" />
              </Form.Item>
            </>
          )}
          <Form.Item>
            <Space style={{ float: 'right' }}>
              <Button onClick={handleCancel}>取消</Button>
              <Button type="primary" htmlType="submit">
                添加
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default BlacklistSettings; 